package com.sample.android.dao;

import java.util.ArrayList;
import java.util.List;

import com.sample.android.entity.Dossier;
import com.sample.android.sqlite.MySQLiteHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DossierDataSource
{

	// Database fields
	private SQLiteDatabase	database;
	private MySQLiteHelper	dbHelper;
	private String[]		allColumns	= { "_id", "libelle", "utilisateur_id" };

	public DossierDataSource(Context context)
	{
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException
	{
		database = dbHelper.getWritableDatabase();
	}

	public void close()
	{
		dbHelper.close();
	}

	public Dossier createDossier(String libelle, long utilisateur_id, long _id)
	{
		ContentValues values = new ContentValues();
		values.put("libelle", libelle);
		values.put("utilisateur_id", utilisateur_id);
		values.put("_id", _id);
		long insertId = database.insert("Dossier", null, values);
		Cursor cursor = database.query("Dossier", allColumns, "_id = "
				+ insertId, null, null, null, null);
		cursor.moveToFirst();
		Dossier newDossier = cursorToDossier(cursor);
		cursor.close();
		return newDossier;
	}

	public Dossier createDossier(Dossier dossier)
	{
		return createDossier(dossier.getLibelle(), dossier.getUtilisateur_id(),
				dossier.getId());
	}

	public void deleteDossier(Dossier dossier)
	{
		long id = dossier.getId();
		System.out.println("Dossier deleted with id: " + id);
		database.delete("Dossier", "_id = " + id, null);
	}

	public List<Dossier> getAllDossiers()
	{
		List<Dossier> dossiers = new ArrayList<Dossier>();

		Cursor cursor = database.query("Dossier", allColumns, null, null, null,
				null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			Dossier dossier = cursorToDossier(cursor);
			dossiers.add(dossier);
			cursor.moveToNext();
		}
		// make sure to close the cursor
		cursor.close();
		return dossiers;
	}

	private Dossier cursorToDossier(Cursor cursor)
	{
		Dossier dossier = new Dossier();
		dossier.setId(cursor.getLong(0));
		dossier.setLibelle(cursor.getString(1));
		dossier.setUtilisateur_id(cursor.getLong(2));
		return dossier;
	}

}
